<?php

namespace App\Store\Controllers\Financial\Business;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\Common;
use App\Store\Models\Order\OrderRecovery;
use App\Store\Models\Order\OrderSales;

/**
 * 销售明细
 */
class SalesInfoController extends Controller
{

    public function getlist(Request $request)
    {
            $store_id = intval($request->store_id);
            if ($store_id <= 0) {
                return response()->json(['code' => '001', 'msg' => '请选择门店']);
            }

            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            if ($accountinfo['type'] == 11) {
                $training = StoreCommon::gettraining($request);
                if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                    return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
                }
            }

            $where = [];
            $where[] = ['store_id', $store_id];
            $where[] = ['audit_status', 2];

            $goods_category_id = intval($request->goods_category_id);
            if ($goods_category_id > 0) {
                $where[] = ['goods_category_id', $goods_category_id];
            }

            $order_at_start = strtotime($request->order_at_start);
            $order_at_end = strtotime($request->order_at_end);
            if ($order_at_start > 0 && $order_at_end > $order_at_start) {
                $where[] = ['order_at', '>=', $order_at_start];
                $where[] = ['order_at', '<=', $order_at_end];
            }

            $shopping_account_id1 = intval($request->shopping_account_id1);
            if ($shopping_account_id1 > 0) {
                $where[] = ['shopping_account_id1', $shopping_account_id1];
            }
            $shopping_account_id2 = intval($request->shopping_account_id2);
            if ($shopping_account_id2 > 0) {
                $where[] = ['shopping_account_id2', $shopping_account_id2];
            }

            $classesset_id = intval($request->classesset_id);
            if ($classesset_id > 0) {
                $where[] = ['classesset_id', $classesset_id];
            }


            $goods_sn_code = $request->goods_sn_code;

            if ($goods_sn_code != '') {
                $where[] = ['goods_sn_code', $goods_sn_code];
            }
            $order_sn = $request->order_sn;


            if ($accountinfo['type'] == 11) {
                $sales_where = $where + [
                        ['total_money', '>', $training['training_min']],
                        ['total_money', '<', $training['training_max']],
                    ];
            } else {
                $sales_where = $where;
            }
            $list1 = OrderSalesGoods::where($sales_where)->select(['id', DB::raw('"1" as type'), 'order_at']);

            $list2 = OrderSalesRecoveryGoods::where($where)->select(['id', DB::raw('"2" as type'), 'order_at']);

            if ($accountinfo['type'] == 11) {
                $recovery_where = $where + [
                        ['money', '>', $training['training_min']],
                        ['money', '<', $training['training_max']],
                    ];
            } else {
                $recovery_where = $where;
            }
            $list3 = OrderRecoveryGoods::where($recovery_where)->select(['id', DB::raw('"3" as type'), 'order_at']);


            if ($order_sn != '') {
                $ids = OrderSales::where('order_sn', 'like', '%' . $order_sn . '%')->pluck('id');
                $ids_r = OrderRecovery::where('order_sn', 'like', '%' . $order_sn . '%')->pluck('id');
                $list1->whereIn('pid', $ids);
                $list2->whereIn('pid', $ids);
                $list3->whereIn('pid', $ids_r);
            }

            $goods_brand_id = intval($request->goods_brand_id);
            if ($goods_brand_id > 0) {
                $list1->where('goods_brand_id', $goods_brand_id);
                $list2->where('1', 2);
                $list2->where('1', 2);
            }


            $isgetall = intval($request->isgetall) ?? 0;
            if ($isgetall == 0) {
                $limit = $request->limit ?? 10;
                $list = $list1->union($list2)->union($list3)->orderBy('order_at', 'desc')->paginate($limit)->toArray();
                $list = Common::paginateDataToArray($list);
            } else {
                $list = $list1->union($list2)->union($list3)->orderBy('order_at', 'desc')->get()->toArray();
                $list = ['list' => $list];
            }

            foreach ($list['list'] as &$val) {
                if ($val['type'] == 1) {
                    //开单
                    $subinfo = OrderSalesGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'classessetinfo'])
                        ->where(['id' => $val['id']])->first();
                    $val['subinfo'] = !empty($subinfo) ? $subinfo->toArray() : [];
                    if (!empty($val['subinfo'])) {
                        // 预存金额要显示预存金额和积分金额的和
                        $val['subinfo']['sub_balance_money'] = ($val['subinfo']['sub_balance_money'] ?? 0) + ($val['subinfo']['sub_pointstobalance'] ?? 0);
                    }


                } elseif ($val['type'] == 2) {
                    // 旧料
                    $val['subinfo'] = OrderSalesRecoveryGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'goods_category', 'classessetinfo'])
                        ->where(['id' => $val['id']])->first();
                    $val['subinfo'] = !empty($val['subinfo']) ? $val['subinfo']->toArray() : [];
                } elseif ($val['type'] == 3) {
                    // 纯回收
                    $val['subinfo'] = OrderRecoveryGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'goods_category', 'classessetinfo'])
                        ->where(['id' => $val['id']])->first();
                    $val['subinfo'] = !empty($val['subinfo']) ? $val['subinfo']->toArray() : [];
                    if(!empty($val['subinfo'])){
                        $val['subinfo']['real_total_money'] = !empty($val['subinfo']['orderinfo']) ? -$val['subinfo']['money'] : 0;
                        $val['subinfo']['real_total_money_with_balance'] = !empty($val['subinfo']['orderinfo']) ? -$val['subinfo']['money'] : 0;
                    }


                }

            }

            if ($request->isdoexport == 1) {
                return $this->doexport($list['list'], $request);
            }

            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);

    }

    /**
     * 导出
     */
    protected function doexport($list,$request)
    {
        $exceldata = [];
        $storeNames = array_unique(array_map(function($item) {
            return $item['subinfo']['storeinfo']['store_name'];
        }, $list));
        $row = [
            ['store_name'=>'销售明细报表'],
            ['store_name'=>'所属门店：'.join(',' ,$storeNames)],

            [
                'store_name' => '所属门店',
                'order_sn' => '订单号',
                'shopping_account_name1' => '导购',
                'shopping_account_name2' => '副导购',
                'goods_sn_code' => '条码',
                'goods_name' => '品名',
                'goods_category_name' => '商品类别',
                'salestype' => '销售类型',
                'recovery_goods_category_name' => '旧料类别',
                'count' => '数量',
                'costgram_fee' => '入库克工费',
                'costpiece_fee' => '入库件工费',
                'gramprice_fee' => '销售克工费',
                'pieceprice_fee' => '销售件工费',
                'gemstone_fee1' => '宝石费1',
                'gemstone_fee2' => '宝石费2',
                'add_fee1' => '附加费1',
                'add_fee2' => '附加费2',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'color' => '颜色',
                'clarity' => '净度',
                'cf_no' => '证书号',
                'piece_weight' => '商品件重',
                'netglod_weight' => '商品金重',
                'weight' => '销售金重',
                'price' => '销售单价',
                'label_price' => '标签价',
                'discount' => '折扣',
                'total_money' => '销售金额',
                'discount_money' => '优惠',
                'sub_coupon_money' => '抵用金额',
                'sub_balance_money' => '预存金额',
                'sub_dold_fee' => '折旧工费',
                'real_total_money' => '实收金额',
                'performance' => '业绩金额',
                'commission_total' => '提成',
                'cost_fee_one' => '单件成本',
                'cost_fee' => '总成本',
                'pay_type_name' => '付款方式',
                'real_total_money_with_balance' => '付款金额',
                'ischange' => '是否已换',
                'goods_pricetype_name' => '价格类型',
                'sales_price' => '销售牌价',
                'old_recovery_price' => '返厂金价',
                'order_at' => '销售时间',
                'mem_real_name' => '会员',
                'mem_mobile' => '电话',
                'remark' => '备注',
            ]
        ];

        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[2]['cost_fee_one']);
            unset($row[2]['cost_fee']);
            unset($row[2]['old_recovery_price']);
        }



        foreach ($list as $vval) {
            $goodsinfo = isset($vval['subinfo']['goodsinfo']) ? json_decode($vval['subinfo']['goodsinfo'], true) : [];

            $exceldata[] = [ //根号type区分
                'store_name' => $vval['subinfo']['storeinfo']['store_name'],
                'order_sn' => $vval['subinfo']['orderinfo']['order_sn'],
                'shopping_account_name1' => $vval['subinfo']['shoppingaccountinfo1'] ? $vval['subinfo']['shoppingaccountinfo1']['real_name'] : '',
                'shopping_account_name2' => $vval['subinfo']['shoppingaccountinfo2'] ? $vval['subinfo']['shoppingaccountinfo2']['real_name'] : '',
                'goods_sn_code' => $vval['subinfo']['goods_sn_code'],
                'goods_name' => $goodsinfo ? $goodsinfo['goods_name'] : '',
                'goods_category_name' => $vval['type']==1? (isset($goodsinfo['goods_category']) ? $goodsinfo['goods_category']['category_name'] : ''):($vval['subinfo']['goods_catefory_name']?? ''),
                'salestype' => $vval['type']==1 ? '销售开单' : ($vval['type']==2 ? '销售换货' :'纯回收开单'),
                'recovery_goods_category_name' => $vval['type'] == 3 ? $vval['subinfo']['goods_category']['category_name'] : '',
                'count' => $vval['subinfo']['count'],
                'costgram_fee' => $goodsinfo ? $goodsinfo['costgram_fee'] / 100 : '',
                'costpiece_fee' => $goodsinfo ? $goodsinfo['costpiece_fee'] / 100 : '',
                'gramprice_fee' => $goodsinfo ? $goodsinfo['gramprice_fee'] / 100 : '',
                'pieceprice_fee' => $goodsinfo ? $goodsinfo['pieceprice_fee'] / 100 : '',
                'gemstone_fee1' => $goodsinfo ? $goodsinfo['gemstone_fee1'] / 100 : '',
                'gemstone_fee2' => $goodsinfo ? $goodsinfo['gemstone_fee2'] / 100 : '',
                'add_fee1' => $goodsinfo ? $goodsinfo['add_fee1'] / 100 : '',
                'add_fee2' => $goodsinfo ? $goodsinfo['add_fee2'] / 100 : '',
                'main_stone_weigth' => $goodsinfo ? $goodsinfo['main_stone_weigth'] : '',
                'main_stone_count' => $goodsinfo ? $goodsinfo['main_stone_count'] : '',
                'other_stone_weigth' => $goodsinfo ? $goodsinfo['other_stone_weigth'] : '',
                'other_stone_count' => $goodsinfo ? $goodsinfo['other_stone_count'] : '',
                'color' => $goodsinfo ? $goodsinfo['color'] : '',
                'clarity' => $goodsinfo ? $goodsinfo['clarity'] : '',
                'cf_no' => $goodsinfo ? $goodsinfo['cf_no'] : '',
                'piece_weight' => $goodsinfo ? $goodsinfo['piece_weight'] : '',
                'netglod_weight' => $goodsinfo ? $goodsinfo['netglod_weight'] : '',
                'weight' => $vval['subinfo']['weight'],
                'price' => $vval['subinfo']['price']>0?$vval['subinfo']['price']/100 : '',
                'label_price' =>  $vval['type'] == 1 ? $vval['subinfo']['label_price'] / 100 : '',
                'discount' => $vval['subinfo']['discount'],
                'total_money' => $vval['type'] == 1 ? $vval['subinfo']['total_money'] / 100 : '',
                'discount_money' => $vval['type'] == 1 ? $vval['subinfo']['discount_money'] / 100 : '',
                'sub_coupon_money' => $vval['type'] == 1 ? $vval['subinfo']['sub_coupon_money'] / 100 : '',
                'sub_balance_money' =>  $vval['type'] == 1 ? $vval['subinfo']['sub_balance_money'] / 100 : '',
                'sub_dold_fee' => $vval['type'] == 1 ? $vval['subinfo']['sub_dold_fee'] / 100 : $vval['subinfo']['dold_fee'] / 100,
                'real_total_money' => $vval['type'] == 1 ? $vval['subinfo']['real_total_money'] / 100 : '',
                'performance' => $vval['subinfo']['performance'] / 100,
                'commission_total' =>  $vval['type'] == 1 ? ($vval['subinfo']['commission1_total'] + $vval['subinfo']['commission2_total']) / 100 : ($vval['type'] == 2 ? ($vval['subinfo']['commission1'] + $vval['subinfo']['commission2']) / 100 : $vval['subinfo']['commission1'] / 100),
                'cost_fee_one' => $vval['type'] == 1 ? bcdiv($vval['subinfo']['cost_fee'], $vval['subinfo']['count'])/100 : '',
                'cost_fee' => $vval['type'] == 1 ? $vval['subinfo']['cost_fee'] / 100 : '',
                'pay_type_name' => $vval['type'] == 1 ? $vval['subinfo']['orderinfo']['pay_type_name'] : '',
                'real_total_money_with_balance' => $vval['type'] == 1 ? $vval['subinfo']['real_total_money_with_balance'] / 100 : $vval['subinfo']['money'] / 100,
                'is_change' => isset($vval['subinfo']['is_exchange']) ? ($vval['subinfo']['is_exchange'] == 2 ? '是' : '否') : '',
                'goods_pricetype_name' => isset($goodsinfo['goods_pricetype']['pricetype_name']) ? $goodsinfo['goods_pricetype']['pricetype_name'] : '',
                'sales_price' => $vval['subinfo']['sales_price'] / 100,
                'old_recovery_price' => $vval['subinfo']['old_recovery_price'] / 100,
                'order_at' => date('Y-m-d H:i:s', $vval['order_at']),
                'mem_real_name' => $vval['subinfo']['memberinfo'] ? $vval['subinfo']['memberinfo']['real_name'] : '',
                'mem_mobile' =>  $vval['subinfo']['memberinfo'] ? $vval['subinfo']['memberinfo']['mobile'] : '',
                'remark' => $vval['subinfo']['remark'],
                'type'=>$vval['type'],
            ];
        }


        $filename = '销售明细导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata,[]), $filename);
    }
}
